home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: usenet.eel.ufl.edu!warwick!bsmail!talisker!nathan
- From: nathan@pact.srf.ac.uk (Nathan Sidwell)
- Subject: Re: Float calculations
- Message-ID: <DM5AtL.C24@uns.bris.ac.uk>
- Sender: usenet@uns.bris.ac.uk (Usenet news owner)
- Nntp-Posting-Host: talisker.pact.srf.ac.uk
- Organization: Inmos
- X-Newsreader: TIN [version 1.2 PL2]
- References: <4eqssf$d9q@camelot.ccs.neu.edu> <DM458u.F1y@microunity.com>
- Date: Fri, 2 Feb 1996 11:05:44 GMT
-
- In article <4eqssf$d9q@camelot.ccs.neu.edu>, jason@ccs.neu.edu (Jason Leatherman) writes:
- |> float a, b;
- |>
- |> printf("%0.10f %0.10f %0.10f\n", 99974.0, 50.0, 99974.0/50.0);
- |>
- |> a = 99974.0;
- |> b = 50.0;
- |> printf("%0.10f %0.10f %0.10f\n", a, b, a/b);
- |> The output is:
- |> 99974.0000000000 50.0000000000 1999.4800000000
- |> 99974.0000000000 50.0000000000 1999.4799804688
- |>
- |> Why do the divisions produce different results? This is probably some
-
- What your really asking is what is the difference between
- 99974.0/50.0
- and
- a = 99974.0, b = 50.0, a/b
-
- The constants have the type double and so the first division is performed
- at double precision. The assignments to a and b convert the doubles to
- floats. Now the division of a by b behaves differently in K&R to ANSI.
-
- In K&R all floating point expressions are evaluated at double precision.
- As the values of a and b are exactly representable at float precision, you'll
- get the same result.
-
- In ANSI floating point expressions are evaluated at float precision, if
- both operands are of type float. If one is of type double, then the
- operation happens at double precision. So in ANSI a/b has a result of type
- float, and in this case the exact result is not representable in a float.
-
- Now with optimization things get a little weirder (hence the
- -fstore-floats option on gcc). The optimizer might realize that
- the result of an expression assigned to a float is still
- sitting in floating point registers, and use that value, rather than
- refetching the value from the variable. Now some hardware keeps floating
- point numbers in registers in a canonical long double form. This could
- mean that the value in the register is different to the value in the
- variable (because it has not been rounded). Most of the time this
- extra precision only helps, but in some cases it breaks code (particularly
- that which is looking for the smallest representable float value).
-
- for instance
- float a;
- double b, c;
-
- b = 99974.0/50.0;
- a = b;
- c = a;
-
- a and b will be different (provided a's been stored), but
- will c be equal to a or to b?
-
- nathan
-
- --
- Nathan Sidwell Holder of the Xmris home page
- Chameleon Architecture Group at SGS-Thomson, formerly Inmos
- http://www.pact.srf.ac.uk/~nathan/ Tel 0117 9707182
- nathan@inmos.co.uk or nathan@bristol.st.com or nathan@pact.srf.ac.uk
-